﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using CrazyCancer.Framework.Communication.Enums;
using CrazyCancer.Framework.Communication.Interfaces;

namespace CrazyCancer.Framework.Communication
{
    public class HttpCommunicator : ICommunicator
    {
        /// <summary>
        /// Gets a response from an HTTP fronted API
        /// </summary>
        /// <param name="requestUrl">URL to communicate with</param>
        /// <param name="requestMethod">Method for getting response (GET or POST)</param>
        /// <returns></returns>
        public WebResponse SendRequest(string requestUrl, RequestMethod requestMethod) 
        {
            return SendRequest(requestUrl, requestMethod, null, null);
        }

        public WebResponse SendRequest(string requestUrl, RequestMethod requestMethod, string userName, string password)
        {
            WebRequest request = WebRequest.Create(requestUrl);
            request.Method = GetResponseMethodAsString(requestMethod);

            if((userName != null)&&(password!=null))
            {
                request.Credentials = GetNetworkCredentials(userName, password);
            }

            WebResponse response = request.GetResponse();
            return response;
        }

        private string GetResponseMethodAsString(RequestMethod requestMethod)
        {
            switch (requestMethod)
            {
                case RequestMethod.POST: { return "POST"; }
                default: { return "GET"; }
            }
        }

        private NetworkCredential GetNetworkCredentials(string userName, string password)
        {
            NetworkCredential credential = new NetworkCredential(userName, password);
            return credential;
        }
    }
}
